import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from '../api/api.service';
import { ApiUrl } from '../api/ApiUrl';
import { CompanyVO } from '../vo/CompanyVO';
import { AlertController } from '@ionic/angular';
import { UserVO } from '../vo/UserVO';
import { ToastController } from '@ionic/angular';
import { AnswerVO } from '../vo/Answervo';

@Component({
  selector: 'app-companydetail',
  templateUrl: './companydetail.page.html',
  styleUrls: ['./companydetail.page.scss'],
})
export class CompanydetailPage implements OnInit {
  iid: any;
  item: CompanyVO;
  iconsultantid: number;
  userItem: UserVO;
  curl: string;
  constructor(private toastController: ToastController,
     public alertController: AlertController, public api: ApiService, public activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.curl = 'assets/image/qiye.png';
    this.iid = this.activatedRoute.snapshot.paramMap.get('iid');
    this.onSearch(this.iid);
    this.iconsultantid = 0;
    if (ApiUrl.user != null) {
      this.userItem = ApiUrl.user;
      this.iconsultantid = this.userItem.iconsultantid;
    }
    console.log(ApiUrl.user);
  }
  onSearch(iid: string) {
    this.api.getItem<CompanyVO>(ApiUrl.getOneCompany, { 'iid': iid }).subscribe(response => {

      if (response === null) {
        console.log('没有数据返回');
        return;
      }
       this.item = response;
       if (this.item.cpicpath === null || this.item.cpicpath === '') {
        this.curl = 'assets/image/qiye.png';
       } else {
        this.curl = ApiUrl.companyUrl + this.item.cpicpath;
       }
       console.log(this.curl);
    }, () => {
      console.log('出错了');
    });
  }
  toConnect() {
    this.api.getItem<AnswerVO>(ApiUrl.insertConnectBybank, {
      'icompany': this.item.iid,
      'ccompany': this.item.cname,
      'ibank': this.userItem.iorgname, 'cbank': this.userItem.corgname, 'iconsultant': this.userItem.iconsultantid
    }).subscribe(response => {
      this.presentToast(response.msg);
    }, () => {
      console.log('出错了');
    });
  }
  async presentAlertConfirm() {
    if (this.iconsultantid === 0 ) {
        this.presentToast('只有金融机构顾问才能使用该功能！');
        return;
    }
    const alert = await this.alertController.create({
      header: '信息与服务',
      message: '<strong>是否联系该企业吗？</strong>',
      buttons: [
        {
          text: '关闭',
          role: 'cancel',
          cssClass: 'secondary',
          handler: (blah) => {
            console.log('Confirm Cancel: blah');
          }
        }, {
          text: '发送',
          handler: () => {
            this.toConnect();
          }
        }
      ]
    });

    await alert.present();
  }
  async presentToast(msg) {
    const toast = await this.toastController.create({
      message: msg,
      duration: 2000
    });
    toast.present();
  }
}
